<template>
  <continer>
    <template slot="search">
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="search"></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="search">查询</el-button>
      <el-button size="mini" @click="importSip" v-functions="['sip_number_import']">导入</el-button>
      <el-button size="mini" @click="addSip" v-functions="['sip_number_insert']">新增</el-button>
    </template>
    <template slot="content">
      <configTable
              :headers="tableHeaders"
              :data="tableData"
              :pagingData="pagingData"
              @pageChange="pageChange"
              @pageSizeChange="pageSizeChange"
              @checkHeadersChange="checkHeadersChange">
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
                    :show-overflow-tooltip="true"
                    :resizable="false"
                    :prop="item.prop"
                    :label="item.label"
                    :key="index"
                    :sortable="item.sortable"
                    v-if="item.show && item.prop !== 'oprate'">
            </u-table-column>
            <u-table-column
                    :label="item.label"
                    :width="68"
                    :key="index"
                    v-if="item.prop === 'oprate' && item.show">
              <template slot-scope="scope">
                <span @click="editSip(scope.row)" class="oprate-span" v-functions="['sip_number_edit']">编辑</span>
                <span @click="deleteSip(scope.row)" class="delete-span oprate-span" v-functions="['sip_number_delete']">删除</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <AddOrEditSip :drawerData="drawer" ref="voiceRef" @refresh="fetchData"></AddOrEditSip>
      <ImportSip ref="ImportRef" @refresh="fetchData"></ImportSip>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/configCommon/table.vue'
import { deepClone } from '@/utils/common'
import AddOrEditSip from './AddOrEditSip.vue'
import ImportSip from './ImportSip.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import { IvrModule } from '@/store/modules/config/ivr'
interface DrawerObj {
    type: string
    form: object
}

interface PageData {
    total: number
    limit: number
    page: number
}
@Component({
  name: 'SipNumber',
  components: { continer, configTable, AddOrEditSip, ImportSip, QuickSearch }
})
export default class extends Vue {
  [x: string]: any
  private drawer: DrawerObj = { type: 'add', form: { number: '', uid: '', codingFormat: ['G711U'], isNAT: false } } // 抽屉中用到的数据
  private pagingData: PageData = { total: 0, limit: 10, page: 1 } // 翻页相关的数据控制
  private agents: object[] = [{}] // 快捷搜索中的应用座席下拉
  private tableHeaders: object[] = [ // 标头配置信息
    { label: 'SIP号', prop: 'number' },
    { label: '状态', prop: 'statusName' },
    { label: '应用座席', prop: 'uidName', sortable: true },
    { label: '添加时间', prop: 'createTime' },
    { label: '注册设备', prop: 'registerDevice' },
    { label: '注册时间', prop: 'registerTime' },
    { label: '操作', prop: 'oprate' }
  ]

  private typeArr: object[] = [{ name: '未注册', _id: 0 }, { name: '已注册', _id: 1 }] // 快捷搜索中的状态下拉

  private quickSearchForm: any = { // 快捷检索数据（时间条件，类型）
    form: {},
    advSearchOptions: [] // 快捷检索的数据(语音文件名称)
  }

  private checkHeaders: [] = [] // 当前展示的表头信息

  private tableData: object[] = [] // table数据

  private addSip () { // 添加sip号码
    (this as any).$refs.voiceRef.openOrCloseDrawer()
    this.drawer = { type: 'add', form: { number: '', password: '', uid: '', codingFormat: ['G711U'], isNAT: false } }
  }

  private importSip () { // 导入sip号码
    (this as any).$refs.ImportRef.openOrCloseDrawer()
  }

  private editSip (row: any) { // 编辑sip号码
    (this as any).$refs.voiceRef.openOrCloseDrawer()
    this.drawer = { type: 'edit', form: { _id: row._id, number: row.number, password: row.password, uid: row.uid, codingFormat: row.codingFormat, isNAT: row.isNAT, registerDevice: row.registerDevice } }
  }

  private search () { // 点击查询
    this.pagingData.page = 1
    this.fetchData(null)
  }

  private pageChange (page) { // 翻页
    this.pagingData.page = page
    this.fetchData(null)
  }

  private pageSizeChange (size) { // 每页多少条数据
    this.pagingData.limit = size
    this.pagingData.page = 1
    this.fetchData(null)
  }

  private deleteSip (row: any) { // 删除sip号码
    this.$confirm(`确定删除【${row.number}】吗`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const data = { url: '/call/action/config/sipNumber/delete', method: 'POST', data: { _id: row._id } }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res && res.success) {
          this.$message({ message: `删除【${row.number}】成功！`, type: 'success' })
          this.fetchData(null)
        }
      })
    }).catch(e => {
      console.log(e)
    })
  }

  private checkHeadersChange (checkList) { // 设置表头
    this.$set(this, 'checkHeaders', checkList)
  }

  private fetchData (addSuccess) { // 查列表
    if (addSuccess) { // 新增回到第一页
      this.pagingData.page = 1
    }
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page }, this.quickSearchForm.form)
    const data = { url: '/call/action/config/sipNumber/query', method: 'POST', data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res && res.success) {
        const list = res.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.pagingData.limit)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.pagingData.page = 1
          } else { // 删除到最后一个回到上一页
            this.pagingData.page = page
            this.fetchData(null)
            return false
          }
        }
        list.forEach((item: any) => {
          const agentObj = this.$store.state.common.publicCache.userListObj[item.uid]
          item.uidName = agentObj ? agentObj.name : '--'
          item.statusName = item.registerStatus ? '已注册' : '未注册'
        })
        this.tableData = list
        this.pagingData.total = res.count || 0
      }
    })
  }

  private beforeMount () {
    const userList = deepClone(this.$store.state.common.publicCache.userList) || []
    userList.unshift({ agentName: '无应用座席', _id: 'noBind' })
    this.agents = userList
    this.quickSearchForm = { // 快捷检索数据（时间条件，类型）
      form: {
        number: '',
        uids: [],
        registerStatuses: []
      },
      advSearchOptions: [ // 快捷检索的数据(语音文件名称)
        { label: 'SIP号', inputType: 'input', placeholder: '请输入SIP号', name: 'number', clearable: true },
        { label: '应用座席', inputType: 'select', clearable: true, multiple: true, selectData: userList, name: 'uids', defaultProp: { label: 'agentName', value: '_id' } },
        { label: '状态', inputType: 'select', clearable: true, multiple: true, selectData: this.typeArr, name: 'registerStatuses' }
      ]
    }
    this.fetchData(null)
  }
}
</script>

<style lang="stylus" scoped>
  .oprate-span,.radio-span
    cursor pointer
    color $c-main
  .delete-span
    color $c-danger
    padding-left 10px
  .radio-span
    width 24px
    height 24px
    display inline-block
    background #fff
    margin 2px 0px 2px 0
    box-shadow 0px 1px 3px 0px rgba(216, 222, 230, 0.9)
    border-radius 50%
    font-size 12px
    color $c-main
    text-align center
    vertical-align middle
    &:last-child
     margin-right 0
     margin-left 10px
</style>
